#ifndef SESSION_H
#define SESSION_H
#include <boost/bind.hpp>
#include <boost/shared_ptr.hpp>
#include <boost/enable_shared_from_this.hpp>
#include <boost/asio.hpp>
#include <iostream>
//#include "Room.h"
#include "Packet.h"
#include "defines.h"
//#include "DBAssist.h"
//#include "MemberSql.h"

using boost::asio::ip::tcp;
using namespace boost::asio;
using namespace boost;
using namespace std;

class Session:public boost::enable_shared_from_this<Session>
{
public:
	Session(boost::asio::io_service& io_service): socket_(io_service),valid(false)
	{
	}

	tcp::socket& socket()
	{
		return socket_;
	}
	void start()
	{
		std::cout<<"session starting ..."<<std::endl;
		char* temp=readPacket();
		//client* ci=(client*)temp;
		
		writePacket(temp,strlen(temp));
		valid=true;
	}
	void do_nothing(){}
	void writePacket(char* p,int l)
	{
		
		Packet packet;
		packet.setBody(p,l);
		boost::asio::write(socket_,buffer(packet.getBuffer(),packet.getBufferLength()));//boost::bind(&Session::do_nothing,shared_from_this()));
	}
	char* readPacket()
	{
		char buf[Packet::HEAD_LENGTH];
		boost::asio::read(socket_,buffer(buf,Packet::HEAD_LENGTH));//bind(&Session::do_nothing,shared_from_this()));
		Packet packet;
		packet.setHeader(buf);
		boost::asio::read(socket_,buffer(packet.getBody(),packet.getBodyLength()));//,bind(&Session::do_nothing,shared_from_this()));
		return packet.getBody();
	}
	void async_writePacket(char* p,int l)
	{
		
		Packet packet;
		packet.setBody(p,l);
		boost::asio::async_write(socket_,buffer(packet.getBuffer(),packet.getBufferLength()),boost::bind(&Session::do_nothing,shared_from_this()));
	}
	char* async_readPacket()
	{
		char buf[Packet::HEAD_LENGTH];
		boost::asio::async_read(socket_,buffer(buf,Packet::HEAD_LENGTH),bind(&Session::do_nothing,shared_from_this()));
		Packet packet;
		packet.setHeader(buf);
		boost::asio::async_read(socket_,buffer(packet.getBody(),packet.getBodyLength()),bind(&Session::do_nothing,shared_from_this()));
		return packet.getBody();
	}
	bool isValid(){return valid;}
private:
	tcp::socket socket_;
	bool valid;
};

typedef boost::shared_ptr<Session> SharedSession;


#endif